<template>
  <el-drawer
    v-model="dialogFormVisible"
    :title="article.id ? '编辑文章' : '新增文章'"
    :direction="direction"
    :before-close="cancel"
  >
    <el-form :model="article" :rules="rules" ref="form">
      <el-form-item label="文章标题" prop="cate_name">
        <el-input v-model="article.title" />
      </el-form-item>
      <el-form-item label="文章分类" prop="cate_alias">
        <el-select v-model="article.cate_id" placeholder="请选择" clearable>
          <el-option
            v-for="cate in cateList"
            :label="cate.cate_name"
            :value="cate.id"
            :key="cate.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="文章封面" prop="cate_name">
        <el-upload
          class="avatar-uploader"
          action=""
          :show-file-list="false"
          :auto-upload="false"
          :on-change="onSelectFile"
        >
          <img v-if="imgUrl" :src="imgUrl" class="avatar" alt="" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="文章内容" prop="cate_alias">
        <div class="editor">
          <quill-editor
            ref="editorRef"
            v-model:content="article.content"
            content-type="html"
            theme="snow"
          ></quill-editor>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="confirm"> 确认 </el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { baseURL } from '@/utils/request'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'

import { addArticle, getArticle, updateArticle } from '@/api/article'
import type { Article, Cate } from '@/types'
import { type DrawerProps, ElMessage } from 'element-plus'
import { nextTick, onMounted, ref } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { getCateList } from '@/api/cate'
import axios from 'axios'

const direction = ref<DrawerProps['direction']>('rtl')
const dialogFormVisible = ref(false)
const getInit = (): Article => {
  return {
    state: '已发布',
  } as Article
}
const article = ref<Article>(getInit())
const imgUrl = ref('')
const cancel = () => {
  article.value = getInit()
  dialogFormVisible.value = false
}
const form = ref()
const editorRef = ref()
nextTick(() => editorRef.value?.setHTML?.(''))

const $searchList = defineEmits(['searchList'])
const confirm = async () => {
  //验证参数
  await form.value.validate()
  //保存or新增
  if (article.value.id) {
    await updateArticle(article.value)
    ElMessage.success('编辑成功')
  } else {
    await addArticle(article.value)
    article.value = getInit()
    ElMessage.success('新增成功')
  }
  dialogFormVisible.value = false
  $searchList('searchList')
}
const cateList = ref<Cate[]>([])

const rules = {
  title: [{ required: true, message: '请输入名称', trigger: 'blue' }],
  cate_id: [{ required: true, message: '请输入别名', trigger: 'blue' }],
  cover_img: [{ required: true, message: '请输入图片', trigger: 'blue' }],
  content: [{ required: true, message: '请输入内容', trigger: 'blue' }],
}
const open = async (id?: number) => {
  dialogFormVisible.value = true
  imgUrl.value = ''
  // editorRef.value.setHTML('')
  if (id) {
    const result = await getArticle(id)
    article.value = { ...result }
    imgUrl.value = baseURL + article.value.cover_img

    article.value.cover_img = await imageUrlToFileObject(imgUrl.value, article.value.cover_img)
  } else {
    article.value = getInit()
  }
}
// 将网络图片地址转换为 File 对象的函数
async function imageUrlToFileObject(imageUrl: string, filename: string) {
  try {
    // 使用 Axios 下载图片数据
    const response = await axios.get(imageUrl, { responseType: 'arraybuffer' })

    // 将下载的数据转换成 Blob 对象
    const blob = new Blob([response.data], {
      type: response.headers['content-type'],
    })

    // 创建 File 对象
    return new File([blob], filename, {
      type: response.headers['content-type'],
    })
  } catch (error) {
    console.error('Error converting image URL to File object:', error)
    return null
  }
}
defineExpose({
  open,
})

const onSelectFile = (uploadFile: any) => {
  imgUrl.value = URL.createObjectURL(uploadFile.raw)
  article.value.cover_img = uploadFile.raw
}

onMounted(async () => {
  cateList.value = await getCateList()
})
</script>

<style scoped>
/* 上传框本身 */
.avatar-uploader ::v-deep(.el-upload) {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  width: 178px;
  height: 178px;
  display: flex;
  align-items: center;
  justify-content: center;

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}

.avatar-uploader ::v-deep(.el-upload:hover) {
  border-color: #409eff;
}

.editor {
  width: 100%;
  min-height: 200px;
}

::v-deep(.ql-editor) {
  min-height: 200px;
}
</style>
